from django.db import IntegrityError
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.generics import CreateAPIView, RetrieveAPIView, RetrieveUpdateAPIView, ListAPIView, DestroyAPIView
from rest_framework.response import Response

from answer.models import Answer, AuestionPicture, AnswerPraiseRelationship, AnswerFocus
from answer.serializer import AnswerDetailSer, AnswerCreateSer, AnswerUpdateSer, AnswerTrueSer, AnswerFalseSer, \
    AnswerFocusListSer, AnswerFocusCreateSer
from questions.models import Question
from utils.permission import IsOwnerOrReadOnly


class AnswerCreateView(CreateAPIView):
    serializer_class = AnswerCreateSer

    def perform_create(self, serializer):
        serializer.save(creator=self.request.user)
    # def perform_create(self, serializer):
    #     picture_str = self.request.data.get('pictures', None)
    #     picture_list = []
    #     if picture_str:
    #         for i in picture_str.split(" "):
    #             img = AuestionPicture.objects.create(image=i)
    #             picture_list.append(img)
    #     serializer.save(creator=self.request.user, pictures=picture_list)


class AnswerDetailView(RetrieveAPIView):
    queryset = Answer.objects.all()
    serializer_class = AnswerDetailSer


class AnswerUpdateView(RetrieveUpdateAPIView):
    permission_classes = (IsOwnerOrReadOnly,)
    queryset = Answer.objects.all()
    serializer_class = AnswerUpdateSer


class AnswerListView(ListAPIView):
    queryset = Answer.objects.all()
    serializer_class = AnswerDetailSer


class AnswerDeleteView(DestroyAPIView):
    permission_classes = (IsOwnerOrReadOnly,)
    queryset = Answer.objects.all()
    serializer_class = AnswerDetailSer


@api_view(['POST'])  # 给回答点赞
def praise_answer(request, **kwargs):
    answer_id = kwargs.get('pk')
    try:
        answer = Answer.objects.get(id=int(answer_id))
    except Answer.DoesNotExist:
        return Response({"detail": "answer does not found."}, status=404)
    user = request.user
    try:
        arl = AnswerPraiseRelationship.objects.get(answer=answer, user=user)
    except AnswerPraiseRelationship.DoesNotExist:
        arl = AnswerPraiseRelationship.objects.create(answer=answer, user=user)
    if arl.praise is False:
        arl.praise = True
        answer.praise += 1
        answer.save()
        arl.save()
        return Response(AnswerTrueSer(answer).data, status=201)
    if arl.praise is True:
        arl.praise = False
        answer.praise -= 1
        answer.save()
        arl.save()
        return Response(AnswerFalseSer(answer).data, status=201)


# -------------------------------------------------------------------


class AnswerFocusListView(ListAPIView):
    serializer_class = AnswerDetailSer

    def get_queryset(self):
        user = self.request.user
        queryset = Answer.objects.filter(answerfocus__creator=user).order_by('-created_time')
        return queryset


class AnswerFocusCreateView(CreateAPIView):
    serializer_class = AnswerFocusCreateSer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        answer_id = self.request.data.get('answer')
        try:
            answer = Answer.objects.get(id=answer_id)
            serializer.save(answer=answer)
        except Answer.DoesNotExist:
            return Response({"detail": "answer does not exist"})
        except IntegrityError:
            return Response({"detail": "This answer has been concerned"})
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class AnswerFocusDeleteView(DestroyAPIView):
    lookup_field = 'answer'  # 传回答id
    permission_classes = (IsOwnerOrReadOnly,)
    queryset = AnswerFocus.objects.all()
    serializer_class = AnswerFocusListSer
